import 'package:cached_network_image/cached_network_image.dart';
import 'package:casdon/app/config/theme/theme_extention.dart';
import 'package:casdon/common/widget/common_loading_widget.dart';
import 'package:casdon/core/logger/log.dart';
import 'package:casdon/modules/recipe/data/model/recipe_placeholder_data.dart';
import 'package:casdon/modules/recipe/data/model/recipe_module_model.dart';
import 'package:casdon/modules/recipe/providers/recipe_provider.dart';
import 'package:casdon/modules/recipe/ui/widgets/recipe_module_style1_content.dart';
import 'package:casdon/modules/recipe/ui/widgets/recipe_module_style2_content.dart';
import 'package:casdon/modules/recipe/ui/widgets/recipe_module_style3_content.dart';
import 'package:casdon/modules/recipe/ui/widgets/recipe_module_style3_showStyle2_content.dart';
import 'package:casdon/auto_router.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

class RecipeModuleSection extends ConsumerStatefulWidget {
  final RecipeModuleModel model;

  const RecipeModuleSection({super.key, required this.model});

  @override
  ConsumerState<RecipeModuleSection> createState() =>
      _RecipeModuleSectionState();
}

class _RecipeModuleSectionState extends ConsumerState<RecipeModuleSection> {
  AsyncValue? _lastModuleListState;
  final int _maxCount = 5;
  @override
  void initState() {
    super.initState();
    // 在每次 Widget 创建时刷新数据，确保获取最新数据
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (mounted) {
        _refreshData();
      }
    });
  }

  @override
  void didUpdateWidget(RecipeModuleSection oldWidget) {
    super.didUpdateWidget(oldWidget);
    // 检测到 widget 更新时，刷新数据（例如父页面下拉刷新时）
    if (oldWidget.model.id != widget.model.id ||
        oldWidget.model != widget.model) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        if (mounted) {
          _refreshData();
        }
      });
    }
  }

  void _refreshData() {
    // 使用 notifier 的 refresh() 方法，避免重新初始化 provider
    final notifier = ref.read(
      recipeModuleContentAsyncProvider(widget.model.id).notifier,
    );
    notifier.refresh();
  }

  @override
  Widget build(BuildContext context) {
    // 监听父页面的 module list provider，当下拉刷新时自动刷新数据
    final moduleListState = ref.watch(recipeModuleListAsyncProvider);
    if (_lastModuleListState != null &&
        _lastModuleListState != moduleListState &&
        moduleListState.hasValue) {
      // 检测到父页面刷新，刷新当前组件数据
      WidgetsBinding.instance.addPostFrameCallback((_) {
        if (mounted) {
          _refreshData();
        }
      });
    }
    _lastModuleListState = moduleListState;

    // 烹饪课堂，style3， 直接展示，不需要进一步请求内容
    if (widget.model.style == RecipeModuleStyle.styleNull) {
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(height: 12.w),
          _buildHeader(widget.model.title, context, widget.model, false),
          _buildContentStyleNull(widget.model, context),
        ],
      );
    }

    final contentState = ref.watch(
      recipeModuleContentAsyncProvider(widget.model.id),
    );
    return contentState.when(
      loading: () => const CommonLoadingWidget(),
      error: (e, _) => Padding(padding: EdgeInsets.all(16.w), child: Text('')),
      data: (state) {
        if (state.data.isEmpty) {
          return const SizedBox.shrink();
        }
        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            SizedBox(height: 12.w),

            _buildHeader(
              widget.model.title,
              context,
              widget.model,
              !(widget.model.style == RecipeModuleStyle.styleNull ||
                  state.data.length <= _maxCount),
            ),
            if (widget.model.style == RecipeModuleStyle.style1)
              RecipeModuleStyle1Content(maxCount: _maxCount, state: state),
            if (widget.model.style == RecipeModuleStyle.style2)
              RecipeModuleStyle2Content(maxCount: _maxCount, state: state),
            if (widget.model.style == RecipeModuleStyle.style3 &&
                widget.model.showStyle == RecipeModuleShowStyle.showStyle1)
              RecipeModuleStyle3Content(state: state),
            if (widget.model.style == RecipeModuleStyle.style3 &&
                widget.model.showStyle == RecipeModuleShowStyle.showStyle2)
              RecipeModuleStyle3Showstyle2Content(
                maxCount: _maxCount,
                state: state,
              ),
          ],
        );
      },
    );
  }

  Widget _buildHeader(
    String title,
    BuildContext context,
    RecipeModuleModel model,
    bool showMore,
  ) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            title,
            style: context.textTheme.headlineMedium!.copyWith(
              color: context.customColorThemeNonNull.textColor1,
            ),
          ),
          if (showMore)
            TextButton(
              style: TextButton.styleFrom(
                padding: EdgeInsets.symmetric(horizontal: 0.w, vertical: 4.h),
                minimumSize: Size.zero,
                tapTargetSize: MaterialTapTargetSize.shrinkWrap,
              ),
              onPressed: () {
                if (model.style == RecipeModuleStyle.style1) {
                  RecipeStyle1ListRoute(
                    title: model.title,
                    modelId: model.id,
                  ).push(context);
                }
                if (model.style == RecipeModuleStyle.style2) {
                  RecipeCollectListRoute(
                    title: model.title,
                    modelId: model.id,
                    style: model.style,
                  ).push(context);
                }
                if (model.style == RecipeModuleStyle.style3) {
                  RecipePromotionListRoute(
                    title: model.title,
                    modelId: model.id,
                  ).push(context);
                }
              },
              child: Text(
                "更多",
                style: context.theme.textTheme.bodyMedium!.copyWith(
                  color: context.colorScheme.primary,
                ),
              ),
            ),
        ],
      ),
    );
  }

  Widget _buildContentStyleNull(
    RecipeModuleModel modelm,
    BuildContext context,
  ) {
    return GestureDetector(
      onTap: () {
        CookCourseRoute(moduleId: modelm.id).push(context);
      },
      child: SizedBox(
        height: 100.h,
        child: Container(
          margin: EdgeInsets.only(right: 12.w, left: 12.w),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              SizedBox(
                width: double.infinity,
                height: 100.h,
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(8),
                  child: CachedNetworkImage(
                    imageUrl: modelm.imgUrl,
                    cacheKey: modelm.id,
                    fit: BoxFit.cover,
                    fadeInDuration: Duration.zero,
                    placeholder: (context, url) => const SizedBox(),
                    errorWidget: (context, url, error) {
                      Log.e("XXXX ${modelm.title} $url", error, null);
                      return Image.network(
                        recipePlaceHolderImgUrl,
                        fit: BoxFit.cover,
                        errorBuilder: (context, error, stackTrace) {
                          return Container(
                            color: Colors.grey[200],
                            child: const Icon(
                              Icons.image_outlined,
                              color: Colors.grey,
                            ),
                          );
                        },
                      );
                    },
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
